package com.naodong.shenluntiku.intergation.rx;

import android.view.View;

import com.jakewharton.rxbinding2.InitialValueObservable;

import io.reactivex.Observer;
import io.reactivex.android.MainThreadDisposable;

/**
 * Created by hujie on 17/5/25.
 */

public class ViewVisibilityChangeObservable extends InitialValueObservable<Boolean> {
    private final View view;
    Listener listener;

    public ViewVisibilityChangeObservable(View view) {
        this.view = view;
    }

    @Override
    protected void subscribeListener(Observer<? super Boolean> observer) {
        listener = new Listener(observer);
        observer.onSubscribe(listener);
    }


    public void setVisible(boolean visible) {
        if (listener != null) {
            listener.onVisiblityChange(visible);
        }
    }

    @Override
    protected Boolean getInitialValue() {
        return view.getVisibility() == View.VISIBLE;
    }


    static final class Listener extends MainThreadDisposable {
        private final Observer<? super Boolean> observer;


        Listener(Observer<? super Boolean> observer) {
            this.observer = observer;
        }

        @Override
        protected void onDispose() {

        }

        public void onVisiblityChange(boolean visible) {
            if (!isDisposed()) {
                this.observer.onNext(visible);
            }
        }


    }
}
